<script setup lang="ts">
import {useUserViewStore} from "@/store/views/sys/admin/userStore";
import {ResetPasswordType, UserVo} from "@/api/sys/admin/user/types";
import {FormInstance, FormRules} from "element-plus";
import {resetPasswordApi} from "@/api/sys/admin/user";
import {storeToRefs} from "pinia";

const store = useUserViewStore()
const {setRePasswordVisible} = store
const {rePasswordVisible, rePasswordForm} = storeToRefs(store)
const ruleRePasswordRef = ref<FormInstance>()
const loading = ref(false)

// 重置密码验证
const rulesOfReset = reactive<FormRules<ResetPasswordType>>({
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 100, message: '昵称长度为6-100', trigger: 'blur'},
  ],
  rePassword: [
    {required: true, message: '请输入确认密码', trigger: 'blur'},
    {min: 6, max: 100, message: '昵称长度为6-100', trigger: 'blur'},
  ]
})

// 打开重置密码
function resetPassword(row: UserVo) {
  setRePasswordVisible(true)
  rePasswordForm.value.id = row.id
  rePasswordForm.value.password = ''
  rePasswordForm.value.rePassword = ''
}

// 提交修改密码
async function submitRePassword(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (rePasswordForm.value.password !== rePasswordForm.value.rePassword) {
        ElMessage.warning("两次密码不一样")
        return;
      }
      loading.value = true
      resetPasswordApi(rePasswordForm.value).then(res => {
        setRePasswordVisible(false)
        ElMessage.success('修改成功')
      }).finally(() => {
        loading.value = false
      })
    } else {
      console.log('错误的字段', fields)
    }
  })

}

</script>

<template>
  <!--  弹出框: 修改密码-->
  <el-dialog draggable destroy-on-close v-model="rePasswordVisible" title="修改密码" width="500">
    <el-form :model="rePasswordForm" label-suffix=":" label-width="100" ref="ruleRePasswordRef" :rules="rulesOfReset">
      <el-form-item label="密码" prop="password">
        <el-input v-model="rePasswordForm.password" type="password" show-password/>
      </el-form-item>
      <el-form-item label="确认密码" prop="rePassword">
        <el-input v-model="rePasswordForm.rePassword" type="password" show-password/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="setRePasswordVisible(false)">取消</el-button>
        <el-button type="primary" @click="submitRePassword(ruleRePasswordRef)" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>